package com.cw.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.cw.subject.common.enums.CateGoryTypeEnum;
import com.cw.subject.common.enums.IsDeletedFlagEnum;
import com.cw.subject.domain.convert.SubjectLabelConverter;
import com.cw.subject.domain.entity.SubjectInfoBO;
import com.cw.subject.domain.entity.SubjectLabelBO;
import com.cw.subject.domain.service.SubjectLabelDomainService;
import com.cw.subject.infra.basic.entity.SubjectCategoryPO;
import com.cw.subject.infra.basic.entity.SubjectLabelPO;
import com.cw.subject.infra.basic.entity.SubjectMappingPO;
import com.cw.subject.infra.basic.service.SubjectCategoryPOService;
import com.cw.subject.infra.basic.service.SubjectLabelPOService;
import com.cw.subject.infra.basic.service.SubjectMappingPOService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SubjectLabelDomainServiceImpl implements SubjectLabelDomainService {

    // 引入infra中的SubjectLabelPOService
    @Resource
    private SubjectLabelPOService subjectLabelPOService;
    // 引入infra中的SubjectMappingPOService(通过subject_mapping表查询出subject_label表中信息)
    @Resource
    private SubjectMappingPOService subjectMappingPOService;
    @Resource
    private SubjectCategoryPOService subjectCategoryPOService;

    /**
     * @author: 江传文
     * @date: 2024/4/20 18:03
     * 新增标签
     */
    @Override
    public Boolean add(SubjectLabelBO subjectLabelBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectLabelDomainServiceImpl.add.bo:{}", JSON.toJSONString(subjectLabelBO));
        }
        // (BO -> PO)
        SubjectLabelPO subjectLabelPO = SubjectLabelConverter.INSTANCE
                .convertBoToLabelPO(subjectLabelBO); // 通过BO转化为PO

        subjectLabelPO.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode()); // 设置is_deleted字段为0(未删除)

        int count = subjectLabelPOService.insert(subjectLabelPO);
        return count > 0; // 插入成功则返回true,不成功返回false
    }

    /**
     * @author: 江传文
     * @date: 2024/4/20 18:03
     * 更新标签
     */
    @Override
    public Boolean update(SubjectLabelBO subjectLabelBO) {
        // (BO -> PO)
        SubjectLabelPO subjectLabelPO = SubjectLabelConverter.INSTANCE
                .convertBoToLabelPO(subjectLabelBO);
        int count = subjectLabelPOService.update(subjectLabelPO);
        return count > 0;
    }

    /**
     * @author: 江传文
     * @date: 2024/4/20 18:04
     * 删除标签
     */
    @Override
    public Boolean delete(SubjectLabelBO subjectLabelBO) {
        // (BO -> PO)
        SubjectLabelPO subjectLabelPO = SubjectLabelConverter.INSTANCE
                .convertBoToLabelPO(subjectLabelBO);
        subjectLabelPO.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode()); // 逻辑删除
        // 使用update方法的SQL即可完成操作
        int count = subjectLabelPOService.update(subjectLabelPO);
        return count > 0;
    }

    /**
     * @author: 江传文
     * @date: 2024/4/20 18:04
     * 查询分类下标签
     */
    @Override
    public List<SubjectLabelBO> queryLabelByCategoryId(SubjectLabelBO subjectLabelBO) {
        // 如果当前分类是一级分类,则查询所有标签
        SubjectCategoryPO subjectCategoryPO = subjectCategoryPOService.queryById(subjectLabelBO.getCategoryId());
        if (CateGoryTypeEnum.PRIMARY.getCode() == subjectCategoryPO.getCategoryType()) {
            SubjectLabelPO subjectLabelPO = new SubjectLabelPO();
            subjectLabelPO.setCategoryId(subjectLabelBO.getCategoryId());
            List<SubjectLabelPO> labelPOList = subjectLabelPOService.queryByCondition(subjectLabelPO);
            return SubjectLabelConverter.INSTANCE.convertPOListToLabelBOList(labelPOList);
        }
        Integer CategoryId = subjectLabelBO.getCategoryId();
        SubjectMappingPO subjectMappingPO = new SubjectMappingPO();
        subjectMappingPO.setCategoryId(CategoryId);
        subjectMappingPO.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectMappingPO> mappingPOList = subjectMappingPOService.queryLabelId(subjectMappingPO);
        // 判空
        if (CollectionUtils.isEmpty(mappingPOList)) {
            return Collections.emptyList();
        }

        /*
         * 使用Java 8引入的Stream API来操作mappingPOList列表中的元素,并将每个元素的标签 ID 提取出来,然后将这些标签 ID 收集到一个新的列表中
         * mappingPOList.stream()：这里调用了 stream() 方法，将 mappingPOList 转换为一个流（Stream），以便后续进行流式操作。
         * map(SubjectMappingPO::getLabelId)：在流中的每个元素（SubjectMappingPO 对象）上调用 map 方法，将其映射为标签 ID。
         * SubjectMappingPO::getLabelId 是一个方法引用，用于获取每个 SubjectMappingPO 对象的标签 ID 属性值。
         * collect(Collectors.toList())：最后调用 toList() 方法，将流中的元素收集到一个新的列表中，并返回该列表。
         */
        List<Integer> labelIdList = mappingPOList.stream().map(SubjectMappingPO::getLabelId).collect(Collectors.toList());

        List<SubjectLabelPO> labelPOList = subjectLabelPOService.batchQueryById(labelIdList);

        List<SubjectLabelBO> boList = new LinkedList<>();
        labelPOList.forEach(labelPO -> {
            SubjectLabelBO bo = new SubjectLabelBO();
            bo.setId(labelPO.getId());
            bo.setLabelName(labelPO.getLabelName());
            bo.setSortNum(labelPO.getSortNum());
            bo.setCategoryId(CategoryId);
            boList.add(bo);
        });
        return boList;
    }

}
